<template>
  <view>
    <view @click="openCalendar">
      <slot>
        <text>{{ displayValue }}</text>
      </slot>
    </view>
    <u-calendar
      :show="show"
      :mode="mode"
      :minDate="minDate"
      :maxDate="maxDate"
      :defaultDate="modelValue"
      :monthNum="monthNum"
      :color="color"
      :showConfirm="true"
      :title="title"
      @close="show = false"
      @confirm="onConfirm"
      :formatter="formatter"
    />
  </view>
</template>

<script>
export default {
  name: 'CalendarPicker',
  props: {
    modelValue: {
      type: [Array, String, Number, Date],
      default: () => []
    },
    mode: {
      type: String,
      default: 'multiple' // 支持multiple
    },
    minDate: {
      type: [String, Number],
      default: ''
    },
    maxDate: {
      type: [String, Number],
      default: ''
    },
    monthNum: {
      type: Number,
      default: 3
    },
    color: {
      type: String,
      default: '#2563eb'
    },
    title: {
      type: String,
      default: '选择'
    },
    formatter: {
      type: Function,
      default: null
    }
  },
  data() {
    return {
      show: false
    }
  },
  computed: {
    displayValue() {
      if (Array.isArray(this.modelValue) && this.modelValue.length > 0) {
        return this.modelValue.map(d => this.formatDate(d)).join(', ')
      } else if (this.modelValue) {
        return this.formatDate(this.modelValue)
      } else {
        return '请选择日期'
      }
    }
  },
  methods: {
    openCalendar() {
      this.show = true
    },
    onConfirm(e) {
      this.show = false
      this.$emit('update:modelValue', e)
      this.$emit('change', e)
    },
    formatDate(val) {
      if (!val) return ''
      const d = new Date(val)
      return `${d.getFullYear()}.${(d.getMonth()+1).toString().padStart(2,'0')}.${d.getDate().toString().padStart(2,'0')}`
    }
  }
}
</script>

<style scoped>
</style> 